Data Types, Variables, and Operators

Object Oriented Programming - Unit I

Data Types in Java

Java is a strongly typed language. Every variable must have a declared data type that determines what kind of data it can hold.

Categories of Data Types

  1. Primitive Data Types - Basic built-in types (8 types)
  2. Non-Primitive Data Types - Reference types (Classes, Arrays, Strings, etc.)

Primitive Data Types

Data Type Size Range Default Value Example
byte 1 byte -128 to 127 0 byte age = 25;
short 2 bytes -32,768 to 32,767 0 short year = 2024;
int 4 bytes -2³¹ to 2³¹-1 0 int count = 1000;
long 8 bytes -2⁶³ to 2⁶³-1 0L long bigNum = 9876543210L;
float 4 bytes ±3.4e-038 to ±3.4e+038 0.0f float price = 99.99f;
double 8 bytes ±1.7e-308 to ±1.7e+308 0.0d double pi = 3.14159;
char 2 bytes 0 to 65,535 (Unicode) '\u0000' char grade = 'A';
boolean 1 bit true or false false boolean flag = true;

Non-Primitive Data Types

  • String - Sequence of characters
  • Arrays - Collection of similar type elements
  • Classes - User-defined data types
  • Interfaces - Abstract types
Key Difference: Primitive types store actual values, while non-primitive types store references (memory addresses) to objects.

Variables in Java

A variable is a named memory location that stores a value of a specific data type.

Variable Declaration and Initialization

// Declaration only dataType variableName; // Declaration with initialization dataType variableName = value; // Multiple declarations dataType var1, var2, var3; // Examples int age; int score = 100; double price, tax, total;

Types of Variables

1. Local Variables

  • Declared inside methods, constructors, or blocks
  • Must be initialized before use
  • Scope is limited to the block where declared
  • No default values
public void calculate() { int x = 10; // Local variable int y; // Must be initialized before use y = 20; System.out.println(x + y); // Valid if(x > 5) { int result = x * y; // Local to if block System.out.println(result); } // System.out.println(result); // Error: result not in scope }

2. Instance Variables

  • Declared inside a class but outside methods
  • Each object has its own copy
  • Automatically initialized with default values
  • Accessed using object reference
public class Student { // Instance variables String name; int age; double gpa; public void displayInfo() { System.out.println("Name: " + name); // Default: null System.out.println("Age: " + age); // Default: 0 System.out.println("GPA: " + gpa); // Default: 0.0 } public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student(); s1.name = "Alice"; s1.age = 20; s2.name = "Bob"; s2.age = 22; s1.displayInfo(); s2.displayInfo(); } }

3. Static Variables (Class Variables)

  • Declared with static keyword
  • Shared among all instances of a class
  • Single copy per class
  • Accessed using class name or object reference
public class Counter { // Static variable static int count = 0; // Instance variable int instanceId; public Counter() { count++; // Increments shared count instanceId = count; // Each object gets unique ID } public void display() { System.out.println("Instance ID: " + instanceId); System.out.println("Total objects created: " + count); } public static void main(String[] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); c1.display(); c2.display(); c3.display(); System.out.println("Final count: " + Counter.count); } }

Operators in Java

Operators are special symbols that perform specific operations on operands (variables or values).

Types of Operators

1. Arithmetic Operators

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 10 / 3 3 (integer division)
% Modulus (Remainder) 10 % 3 1
public class ArithmeticDemo { public static void main(String[] args) { int a = 10, b = 3; System.out.println("Addition: " + (a + b)); // 13 System.out.println("Subtraction: " + (a - b)); // 7 System.out.println("Multiplication: " + (a * b)); // 30 System.out.println("Division: " + (a / b)); // 3 System.out.println("Modulus: " + (a % b)); // 1 // Floating point division double c = 10.0, d = 3.0; System.out.println("Float Division: " + (c / d)); // 3.333... } }

2. Relational Operators

Used to compare two values. Returns boolean result (true or false).

Operator Name Example Result
== Equal to 5 == 3 false
!= Not equal to 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 5 <= 3 false

3. Logical Operators

Used to combine multiple conditions.

Operator Name Description Example
&& Logical AND Returns true if both conditions are true (5 > 3) && (8 > 5) → true
|| Logical OR Returns true if at least one condition is true (5 > 3) || (8 < 5) → true
! Logical NOT Reverses the boolean value !(5 > 3) → false

4. Assignment Operators

Operator Example Equivalent to
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3

5. Unary Operators

Operators that work with a single operand.

Operator Name Description Example
++ Increment Increases value by 1 x++ or ++x
-- Decrement Decreases value by 1 x-- or --x
+ Unary plus Indicates positive value +5
- Unary minus Negates an expression -5
! Logical NOT Inverts boolean value !true
public class UnaryDemo { public static void main(String[] args) { int a = 5; // Post-increment System.out.println("Post-increment:"); System.out.println(a++); // Prints 5, then a becomes 6 System.out.println(a); // Prints 6 // Pre-increment System.out.println("Pre-increment:"); System.out.println(++a); // a becomes 7, then prints 7 // Unary minus int b = -10; System.out.println("Unary minus: " + (-b)); // Prints 10 // Logical NOT boolean flag = true; System.out.println("Logical NOT: " + (!flag)); // Prints false } }

6. Ternary Operator

A shorthand way to write if-else statements.

// Syntax variable = (condition) ? expressionTrue : expressionFalse; // Example int age = 20; String result = (age >= 18) ? "Adult" : "Minor"; System.out.println(result); // Output: Adult // Finding maximum of two numbers int x = 10, y = 20; int max = (x > y) ? x : y; System.out.println("Maximum: " + max); // Output: 20

Practical Examples

Example 1: Student Grade Calculator

public class GradeCalculator { public static void main(String[] args) { // Variables String studentName = "John Doe"; int mathMarks = 85; int scienceMarks = 92; int englishMarks = 78; // Calculations using operators int totalMarks = mathMarks + scienceMarks + englishMarks; double average = (double) totalMarks / 3; // Grade determination using ternary operator char grade = (average >= 90) ? 'A' : (average >= 80) ? 'B' : (average >= 70) ? 'C' : (average >= 60) ? 'D' : 'F'; // Output using logical operators boolean passed = average >= 60; boolean distinction = average >= 85; System.out.println("=== Student Report ==="); System.out.println("Name: " + studentName); System.out.println("Total Marks: " + totalMarks + "/300"); System.out.println("Average: " + String.format("%.2f", average) + "%"); System.out.println("Grade: " + grade); System.out.println("Status: " + (passed ? "Passed" : "Failed")); if(distinction) { System.out.println("Congratulations! Distinction achieved!"); } } }

Example 2: Temperature Converter

public class TemperatureConverter { public static void main(String[] args) { double celsius = 25.0; double fahrenheit, kelvin; // Convert Celsius to Fahrenheit fahrenheit = (celsius * 9.0/5.0) + 32; // Convert Celsius to Kelvin kelvin = celsius + 273.15; System.out.println("Temperature Conversions:"); System.out.println(celsius + "°C = " + fahrenheit + "°F"); System.out.println(celsius + "°C = " + kelvin + "K"); // Check temperature ranges using relational operators String weather; if(celsius < 0) { weather = "Freezing"; } else if(celsius < 10) { weather = "Cold"; } else if(celsius < 25) { weather = "Mild"; } else if(celsius < 35) { weather = "Warm"; } else { weather = "Hot"; } System.out.println("Weather condition: " + weather); } }

Example 3: Bank Account Simulation

public class BankAccount { // Instance variables String accountHolder; double balance; // Static variable static double interestRate = 0.05; public BankAccount(String holder, double initialBalance) { this.accountHolder = holder; this.balance = initialBalance; } public void deposit(double amount) { if(amount > 0) { balance += amount; System.out.println("Deposited: $" + amount); System.out.println("New balance: $" + balance); } else { System.out.println("Invalid deposit amount!"); } } public void withdraw(double amount) { if(amount > 0 && amount <= balance) { balance -= amount; System.out.println("Withdrawn: $" + amount); System.out.println("New balance: $" + balance); } else { System.out.println("Invalid withdrawal amount!"); } } public void calculateInterest() { double interest = balance * interestRate; balance += interest; System.out.println("Interest added: $" + interest); System.out.println("New balance: $" + balance); } public static void main(String[] args) { BankAccount account = new BankAccount("Alice Smith", 1000.0); account.deposit(500.0); account.withdraw(200.0); account.calculateInterest(); System.out.println("Final balance: $" + account.balance); } }

Best Practices and Guidelines

Variable Naming Conventions

Rules (Must Follow):

  • Must begin with a letter (a-z, A-Z), underscore (_), or dollar sign ($)
  • After the first character, can contain letters, digits, underscores, or dollar signs
  • Cannot use Java keywords (int, class, public, etc.)
  • Case-sensitive (age and Age are different variables)
  • No spaces allowed

Conventions (Best Practices):

  • Use camelCase for variable names: studentName, totalMarks
  • Use UPPERCASE for constants: MAX_VALUE, PI
  • Make names meaningful and descriptive
  • Avoid single letter names except for loop counters (i, j, k)
// Good naming conventions int studentAge; double accountBalance; boolean isEligibleForDiscount; final int MAX_ATTEMPTS = 3; // Poor naming conventions int a; double bal; boolean flag;

Operator Precedence

Operators are evaluated in order of precedence. Use parentheses to make your intentions clear.

Precedence Operator Description
1 (Highest) ++, -- Postfix increment/decrement
2 ++, --, +, -, ! Unary operators
3 *, /, % Multiplicative
4 +, - Additive
5 <, <=, >, >= Relational
6 ==, != Equality
7 && Logical AND
8 || Logical OR
9 ?: Ternary
10 (Lowest) =, +=, -=, *=, /=, %= Assignment
// Example of operator precedence int result = 5 + 3 * 2; // 5 + (3 * 2) = 11 int result2 = (5 + 3) * 2; // (5 + 3) * 2 = 16 // Complex expression with precedence boolean flag = 5 > 3 && 10 < 20 || 8 == 8; // Evaluated as: (5 > 3) && (10 < 20) || (8 == 8) // true && true || true // true || true // true

Type Casting

Converting a value from one data type to another.

Widening (Implicit) Casting

Automatic conversion from smaller to larger data type. No data loss.

int num = 100; long bigNum = num; // int to long float decimal = bigNum; // long to float double precise = decimal; // float to double

Narrowing (Explicit) Casting

Manual conversion from larger to smaller data type. May cause data loss.

double d = 99.99; int i = (int) d; // Explicit casting required System.out.println(i); // Output: 99 (decimal part lost) long l = 1000000L; int j = (int) l; System.out.println(j); // Output: 1000000
Important: Be careful with type casting as it can lead to data loss or unexpected results. Always validate conversions when dealing with critical data.

Summary

Key Points Covered:

  • Data Types: 8 primitive types and non-primitive reference types
  • Variables: Local, instance, and static variables with different scopes
  • Operators: Arithmetic, relational, logical, assignment, unary, and ternary
  • Best Practices: Naming conventions, operator precedence, type casting
  • Practical Applications: Real-world examples combining all concepts
Remember: Understanding data types, variables, and operators is fundamental to Java programming. Master these concepts to build a strong foundation for advanced topics.